package com.dajun.listener;

import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.idm.api.User;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 *  审批节点监听类
 */
@Component("approvalResultListener")
public class ApprovalResultListener implements TaskListener {
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;

    @Override
    public void notify(DelegateTask task) {
        if ("complete".equals(task.getEventName())) {
            // todo 审批节点监听类，后续根据需求修改业务
            //获取当前节点审批人id
            String assignee = task.getAssignee();

            //更具职位/岗位/部门信息获取动态审批人信息:如根据岗位获取审批人
            String variable = (String) runtimeService.getVariable(task.getProcessInstanceId(), "postId");
            List<User> users = identityService.createUserQuery().memberOfGroup("managers_" + variable).list();

            // 1. 获取当前审批结果
            Boolean approved = (Boolean) task.getVariable("approved");

            // 2. 只有通过时才更新计数器
            if (Boolean.TRUE.equals(approved)) {
                Integer currentApproved = (Integer) task.getVariable("nrOfApproved");
                task.setVariable("nrOfApproved", currentApproved + 1);

                System.out.printf(
                        "审批人 %s 已通过，当前通过数 %d/%d%n",
                        task.getVariable("approver"),
                        currentApproved + 1,
                        task.getVariable("requiredApprovals")
                );
            }
        }
    }
}
